package com.java.architect.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLockImpl implements RedissonLock {
    private Logger log = LoggerFactory.getLogger(RedissonLockImpl.class);
    @Autowired
    private RedissonClient redissonClient;

    public RedissonLockImpl() {
    }

    public boolean tryLock(String key, long waitTime, TimeUnit unit) {
        try {
            RLock lock = this.redissonClient.getLock(key);
            return null == lock ? false : lock.tryLock(waitTime, unit);
        } catch (InterruptedException var6) {
            this.log.error("tryLock is error,key=>{},waitTime=>{},unit={},msg=>{}", new Object[]{key, waitTime, unit, var6});
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public boolean tryLock(String key, long waitTime, long leaseTime, TimeUnit unit) {
        try {
            RLock lock = this.redissonClient.getLock(key);
            return null == lock ? false : lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException var8) {
            this.log.error("tryLock is error,key=>{},waitTime=>{},leaseTime={},unit={},msg=>{}", new Object[]{key, waitTime, leaseTime, unit, var8});
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void unlock(String key) {
        RLock lock = this.redissonClient.getLock(key);
        if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
            this.log.error("unlock key=>{} is success.", key);
        }

    }
}
